<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Signin extends CI_Controller {
	
	function __construct()
	{
		parent::__construct();
	}
	
	/**
	 * Default Signin page
	 *
	 * @access	public
	 * @output	signin.tpl
	 */
	public function index()
	{		
		$data['title'] = "Sign In";		
		$this->parser->parse("signin/signin.tpl", $data);
	}
	
	/**
	 * Authenticate username/email and password
	 *
	 * @access		public
	 * @redirect	Success: 		/
	 *				Unsuccessful: 	/signin
	 */
	public function authenticate()
	{
		$this->load->helper(array('form', 'url'));
		$this->load->library(array('form_validation'));
		
		$this->form_validation->set_rules('username', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');
				 
		if ($this->form_validation->run() == FALSE)
		{
			$this->session->set_flashdata('notice', 'Username and/or password was incorrect');
			redirect('/home');
		} else {
			$this->load->model(array('User_model'));
		
			$user = $this->User_model->get_user_by_login($this->input->post('username'), $this->input->post('password'));
			
			if($user==NULL)
			{
				/* Username and/or Password was incorrect */
				$this->session->set_flashdata('notice', 'Username and/or password was incorrect');
				redirect('/home');
			} else {
				$userData = array(
								'id' 		 => $user->id,
								'username'   => $user->username,
								'email'      => $user->email,
								'lastOnline' => $user->date_lastonline,
								'loggedIn'   => TRUE
								);
				
				$this->session->set_userdata($userData);
				redirect('/profile');
			}
		}
	}
	
	/**
	 * Signout function
	 *
	 * @access		public
	 * @redirect 	/
	 */
	public function signout()
	{
		$this->load->helper(array('url'));
		/* Destroy Session */
		$this->session->sess_destroy();
		redirect('/');
	}
	
}
?>